class AccountsController < ApplicationController
  skip_before_filter :sso, :prepare_session, :check_guest_mode

  verify :method => :post, :only => [:apply], :redirect_to => { :controller => :platform, :action => :index}

  def index
    # ログイン中かつゲストで無い場合はmypageへ
    if( session[:user_code] and not session[:user_code] == '000000')
      redirect_to :controller => :mypage
      return false
    end

    @applied_account = AppliedAccount.new
  end

  def apply
    params[:applied_account][:section] ||= ""
    @applied_account = AppliedAccount.new(params[:applied_account])
    if @applied_account.save
      UserMailer.deliver_sent_signup_confirm(@applied_account.email, url_for(:controller => :accounts, :action => :applied_confirm, :id => @applied_account.onetime_code))
      redirect_to :action => :sent_mail
    else
      render :action => :index
    end
  end

  def sent_mail
  end

  def applied_confirm
    if applied_account = AppliedAccount.find_by_onetime_code(params[:id])
      account = Account.new do |a|
        a.code = a.name = applied_account.code
        a.password = applied_account.password
        a.password_confirmation = applied_account.password
        a.section = applied_account.section
        a.email = applied_account.email
      end

      user_uid = UserUid.new do |u|
        u.uid = account.code
        u.uid_type = UserUid::UID_TYPE[:master]
      end

      user_profile = UserProfile.new do |u|
        u.birth_month = 1
        u.hobby = ''
        u.join_year = 2008
        u.blood_type = 1
        u.address_1 = 1
        u.alma_mater = '非公開'
        u.birth_day = 1
        u.disclosure = 0
        u.gender_type = 1
        u.address_2 = '非公開'
        u.introduction = ''
        u.hometown = 1
      end

      user_access = UserAccess.new(:last_access => Time.now, :access_count => 0)

      user = User.new do |u|
        u.name = account.name
        u.extension = 000000
        u.introduction = 'よろしくお願いします。'
        u.retired = 0
        u.section = 'ユーザ'
        u.email = account.email
        u.user_uids << user_uid
        u.user_profiles << user_profile
        u.user_access = user_access
      end

      Account.transaction do
        account.save! # 失敗はあり得ないので
        ActiveRecord::Base.connection.execute("update accounts set crypted_password = '#{applied_account.password}' where id = #{account.id}")
        user.save!
        applied_account.destroy
      end

      redirect_to :action => :complete
      return false
    else
      redirect_to :action => :failure
      return false
    end
  end

  def complete
  end

  def failure
  end

  def ado_check_code
    render :text => AppliedAccount.check_code(params[:code])
  end
end
